package com.xxx.controller;

import com.xxx.common.Code;
import com.xxx.common.Result;
import com.xxx.pojo.Employee;
import com.xxx.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private EmployeeService service;


    @RequiresGuest
    @PostMapping("/okLogin")
    public Result okLogin(HttpServletRequest request, @RequestBody Employee employee){
//        Employee e = service.okLogin(employee.getUsername(), employee.getPassword());
//        System.out.println(employee);


//        String encode = BCrypt.hashpw(employee.getPassword(),BCrypt.gensalt());

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(employee.getUsername(),employee.getPassword());

//        log.info("token:{}",token.toString());

        Result r = new Result();
        try {
            //经过shiro进行登入操作
            subject.login(token);
        } catch (UnknownAccountException e){
            r.setCode(Code.GET_ERR);
            r.setMessage("用户名不存在！！");
            return r;
        }catch (IncorrectCredentialsException e){
            r.setCode(Code.GET_ERR);
            r.setMessage("用户名或密码错误！！！");
            return r;
        }
//        HttpSession session = request.getSession();

        r.setCode(Code.GET_OK);
//        session.setAttribute("employeeId", e.getId());
//        session.setMaxInactiveInterval(60 * 30);

        return r;
    }


    @GetMapping("/logout")
    public void loginOut( HttpServletResponse response) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        response.sendRedirect("http://localhost:8080/background/login/login.html");
    }
}
